import axios, { AxiosRequestConfig } from "axios";
import { getCookie, setCookie } from "@/utils/token";
// 加密解密
import aes from "@/utils/aes";
import { ElMessage } from "element-plus";
import { _getLocalItem, _setLocalItem } from "../tools";
const env = process.env.NODE_ENV || 'development'
const Instance = axios.create({
  timeout: 90000,
  baseURL: env === "development" ? "http://localhost:3000" : "/api/",
  // cors origin, open at production
  withCredentials: env === "development" ? false : true,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
  },
});

async function refreshTokens() {
  const res = await Instance.get("/user/refresh", {
    params: {
      refreshToken: aes.aesDecrypt(_getLocalItem("refresh_token")),
    },
  });
  return res;
}
interface PendingTask {
  config: AxiosRequestConfig;
  resolve: Function;
}
let refreshing = false;
const queue: PendingTask[] = [];

// 添加请求拦截器
Instance.interceptors.request.use(
  function (config: any) {
    // jwt
    const whiteList = [
      "/user/login/",
      "/blog/queryBlogList/",
      "/user/refresh/",
    ];
    const noToken = whiteList.some((url) => config.url.includes(url));
    const token = getCookie("accessToken") || "";
    if (!noToken) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    // if (
    //   config.method === 'post' &&
    //   config.headers['Content-Type'] ===
    //   'application/x-www-form-urlencoded;charset=utf-8'
    // ) {
    //   config.data = qs.stringify(config.data);
    // }
    // 在发送请求之前做些什么
    return config;
  },
  function (error: any) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
Instance.interceptors.response.use(
  function (response: any): any {
    if (response.status == 200 || response.status == 201) {
      return {
        data: response.data,
        status: response.status,
        message: response.statusText,
      };
    } else {
      ElMessage.error(response.data);
    }
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
  },
  async function (error: any) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    if(!error.response) {
      ElMessage.error("网络错误");
      return error
    }
    let { config } = error.response;
    if (refreshing) {
      return new Promise((resolve) => {
        queue.push({
          config,
          resolve,
        });
      });
    }
    // error.message === 'Request failed with status code 401'
    if (
      // ERR_BAD_REQUEST
      error?.status === 401 &&
      !config?.url?.includes("/user/refresh")
    ) {
      refreshing = true;

      const res = await refreshTokens();

      refreshing = false;

      if (res?.status === 200) {
        setCookie("accessToken", res.data.access_token, { expires: 1 });
        _setLocalItem(
          "access_token",
          aes.aesEncrypt(res.data.access_token) || ""
        );
        _setLocalItem(
          "refresh_token",
          aes.aesEncrypt(res.data.refresh_token) || ""
        );
        queue.forEach(({ config, resolve }) => {
          resolve(Instance(config));
        });
        return Instance(config);
      } else {
        ElMessage.error("请重新登录");
        return Promise.reject(res.data);
      }
    } else if (error?.code == "ERR_NETWORK") {
      ElMessage.error("网络错误");
    } else if (error?.message?.indexOf("timeout") != -1) {
      ElMessage.error("网络超时");
    } else {
      return Promise.reject(error);
    }
  }
);
// code
// :
// "ERR_NETWORK"
export default Instance;

// import axios from 'axios'
// import { ElMessage } from 'element-plus'
// // 引入定义的 router 实例
// import router from '../router'

// const request: any = axios.create({
//   baseURL: '/api',
//   timeout: 600000,
// })
// function redirectLogin() {
//   router?.push('/login')
// }
// request.interceptors.response.use(
//   (response: any) => {
//   	// 未登录回到登录页
//     if (response.data?.code === '401') {
//     	return router?.push('/login')
//     }
//     if (response.data.code !== '200') {
//       ElMessage.error(response.data.msg)
//        return Promise.reject(response.data)
//      } else {
//        return response.data.data
//      }
//   },
//   (error: any) => {
//     return Promise.reject(error)
//   }
// )
// export default request
